#include "HistoricalData.h"
#include "ui_HistoricalData.h"
#include "Tools/MyUrl.h"
#include "Models/DeviceData.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

HistoricalData::HistoricalData(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::HistoricalData)
{
    ui->setupUi(this);

    this->comBoxDeviceInit();
    this->chart_temperature_init();

    // chart_temperature = nullptr;
    // series_temperature = nullptr;
    // chartView_temperature = nullptr;
    // axisX_temperature = nullptr;

    this->calendarInit();
}


HistoricalData::~HistoricalData()
{
    delete ui;
}

void HistoricalData::calendarInit()
{
    this->ui->dateTimeEdit_startTime->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
    this->ui->dateTimeEdit_startTime->setDateTime(QDateTime::currentDateTime().addDays(-1));

    this->ui->dateTimeEdit_endTime->setDisplayFormat("yyyy-MM-dd HH:mm:ss");
    this->ui->dateTimeEdit_endTime->setDateTime(QDateTime::currentDateTime());
}

void HistoricalData::comBoxDeviceInit()
{
    QNetworkAccessManager* manager = new QNetworkAccessManager();
    connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply *reply){
        QJsonParseError parseError;
        QJsonDocument jsonData = QJsonDocument::fromJson(reply->readAll(), &parseError);

        if (parseError.error != QJsonParseError::NoError)
        {
            qDebug() << "JSON 解析失败：" << parseError.errorString() << __LINE__ << __FILE_NAME__;
            return;
        }

        QJsonArray deviceArray = jsonData.array();

        for(const QJsonValue &value: deviceArray)
        {
            QJsonObject deviceJson = value.toObject();
            this->ui->comboBox_device->addItem(deviceJson["device_id"].toString());
        }
    });
    QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::deviceSelect));
    request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    manager->get(*request);
}

void HistoricalData::chart_temperature_init()
{
    // 布局初始化
    this->layout_temperature = new QVBoxLayout();
    this->ui->widget_temperature->setLayout(this->layout_temperature);
    this->ui->widget_temperature->setContentsMargins(0, 0, 0, 0);

    // 曲线系列设置
    this->series_temperature = new QLineSeries();
    this->series_temperature->setUseOpenGL(true);

    this->series_temperature->setName("历史数据变化曲线");
    this->series_temperature->setPen(QPen(QColor(59, 130, 246), 2)); // 淡蓝色曲线
    this->series_temperature->setPointsVisible(true);
    this->series_temperature->setPointLabelsVisible(false);

    // 区域填充
    QAreaSeries *areaSeries = new QAreaSeries(series_temperature);
    areaSeries->setUseOpenGL(true);

    // 淡蓝渐变
    QLinearGradient gradient(QPointF(0, 0), QPointF(0, 1));
    gradient.setColorAt(0, QColor(59, 130, 246, 100)); // 上半透明淡蓝
    gradient.setColorAt(1, QColor(59, 130, 246, 10));  // 下部几乎透明
    gradient.setCoordinateMode(QGradient::ObjectBoundingMode);

    areaSeries->setBrush(gradient);
    areaSeries->setPen(QPen(Qt::NoPen)); // 边界线隐藏


    // 图表设置
    this->chart_temperature = new QChart();
    this->chart_temperature->addSeries(areaSeries); // 添加填充区域系列
    this->chart_temperature->addSeries(series_temperature); // 添加线系列（在区域上方）
    //this->chart_temperature->setTitle("环境温度监测折线图");

    // 美化标题
    QFont titleFont = chart_temperature->titleFont();
    titleFont.setBold(true);
    titleFont.setPointSize(12);
    titleFont.setFamily("微软雅黑 UI");
    chart_temperature->setTitleFont(titleFont);
    chart_temperature->setTitleBrush(QBrush(QColor(60, 60, 60))); // 深灰色标题

    // 设置动画效果
    this->chart_temperature->setAnimationOptions(QChart::SeriesAnimations);
    this->chart_temperature->setAnimationDuration(1000); // 动画持续时间1秒

    // X轴（时间轴）设置
    this->axisX_temperature = new QDateTimeAxis();
    this->axisX_temperature->setTitleText("时间");
    this->axisX_temperature->setFormat("HH:mm:ss");
    this->axisX_temperature->setRange(QDateTime::currentDateTime().addSecs(-300),
                                      QDateTime::currentDateTime());
    this->axisX_temperature->setTickCount(6); // 6个刻度
    this->axisX_temperature->setGridLineVisible(true);
    this->axisX_temperature->setGridLinePen(QPen(QColor(220, 220, 220), 1, Qt::DotLine));
    this->axisX_temperature->setLabelsFont(QFont("微软雅黑 UI", 9)); // 设置字体，支持中文

    // Y轴（温度轴）设置
    this->axisY = new QValueAxis();
    this->axisY->setTitleText("数值");
    this->axisY->setRange(0, 100); // y轴范围
    this->axisY->setTickCount(7);  // 刻度数量
    this->axisY->setGridLineVisible(true);
    this->axisY->setGridLinePen(QPen(QColor(220, 220, 220), 1, Qt::DotLine));
    this->axisY->setLabelsFont(QFont("微软雅黑 UI", 9)); // 设置字体，支持中文
    this->axisY->setTitleBrush(QBrush(QColor(80, 80, 80))); // 轴标题颜色

    // 添加坐标轴
    this->chart_temperature->addAxis(this->axisX_temperature, Qt::AlignBottom);
    this->series_temperature->attachAxis(this->axisX_temperature);
    areaSeries->attachAxis(this->axisX_temperature);

    this->chart_temperature->addAxis(axisY, Qt::AlignLeft);
    this->series_temperature->attachAxis(axisY);
    areaSeries->attachAxis(axisY);

    // 图例设置
    chart_temperature->legend()->setVisible(true);
    chart_temperature->legend()->setAlignment(Qt::AlignTop);
    chart_temperature->legend()->setFont(QFont("微软雅黑 UI", 10));

    // 图表视图设置
    this->chartView_temperature = new QChartView(this->chart_temperature);
    this->chartView_temperature->setRenderHint(QPainter::Antialiasing);

    // 设置图表背景
    chartView_temperature->setBackgroundBrush(QBrush(QColor(255, 255, 255)));
    chart_temperature->setBackgroundBrush(QBrush(QColor(255, 255, 255)));

    // 添加边框
    //chartView_temperature->setStyleSheet("border: 1px solid #e0e0e0; border-radius: 4px;");

    // 添加到布局
    this->layout_temperature->addWidget(this->chartView_temperature);

    // 添加数据提示（悬停时显示数值）
    QToolTip::setFont(QFont("微软雅黑 UI", 10));
    connect(series_temperature, &QLineSeries::hovered,
            this, [=](const QPointF &point, bool state) {
                if (state) {
                    QDateTime time = QDateTime::fromMSecsSinceEpoch(point.x());
                    QString tooltip = QString("%1\n数值: %2")
                                          .arg(time.toString("HH:mm:ss"))
                                          .arg(point.y(), 0, 'f', 1);
                    QToolTip::showText(QCursor::pos(), tooltip);
                }
            });
}

void HistoricalData::on_pushButton_search_clicked()
{
    QNetworkAccessManager* manager = new QNetworkAccessManager();
    connect(manager, &QNetworkAccessManager::finished, this, [=](QNetworkReply* reply){
        QJsonParseError parseError;
        QJsonDocument jsonData = QJsonDocument::fromJson(reply->readAll(), &parseError);

        if (parseError.error != QJsonParseError::NoError)
        {
            qDebug() << "JSON 解析失败：" << parseError.errorString() << __LINE__ << __FILE_NAME__;
            return;
        }

        QVector<DeviceData*> temp_deviceData;
        QJsonArray deviceArray = jsonData.array();
        for(const QJsonValue &value: deviceArray)
        {
            QJsonObject deviceJson = value.toObject();


            QString device_id = deviceJson.value("device_id").toString();
            QString start_time = deviceJson.value("start_time").toString();
            QString end_time = deviceJson.value("end_time").toString();

            QString dataStr = deviceJson.value("data").toString();
            QJsonDocument dataDoc = QJsonDocument::fromJson(dataStr.toUtf8(), &parseError);
            if (parseError.error != QJsonParseError::NoError)
            {
                qDebug() << "data字段解析失败" << parseError.errorString();
                continue;
            }
            if (!dataDoc.isArray())
            {
                qDebug() << "data字段格式错误：不是数组";
                continue;
            }

            QJsonArray dataArray = dataDoc.array();
            QVector<int> temp_dataArray;
            for (const QJsonValue& dataValue : dataArray)
            {
                temp_dataArray.push_back(dataValue.toString().toInt());
            }
            temp_deviceData.push_back(new DeviceData(device_id, temp_dataArray, start_time, end_time));
        }
        this->plotData(temp_deviceData);
    });

    QJsonObject jsonData;
    jsonData["device_id"] = this->ui->comboBox_device->currentText();
    jsonData["start_time"] = this->ui->dateTimeEdit_startTime->dateTime().toString("yyyy-MM-dd HH:mm:ss");
    jsonData["end_time"] = this->ui->dateTimeEdit_endTime->dateTime().toString("yyyy-MM-dd HH:mm:ss");

    QJsonDocument doc(jsonData);
    QNetworkRequest* request = new QNetworkRequest(QUrl(MyUrl::dataSelect));
    request->setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    manager->post(*request, doc.toJson(QJsonDocument::Compact));

}

void HistoricalData::plotData(QVector<DeviceData*> allData)
{
    qDebug() << "开始绘制" << __LINE__ << __FILE_NAME__;

    if (allData.isEmpty())
    {
        qDebug() << "数据为空" << __LINE__ << __FILE_NAME__;
        return;
    }
//=================================================================
// 获取最大时间和最小时间
//=================================================================
    QDateTime globalStart = QDateTime::fromString(allData[0]->m_startTime, "yyyy-MM-dd HH:mm:ss");
    QDateTime globalEnd   = QDateTime::fromString(allData[0]->m_endTime,   "yyyy-MM-dd HH:mm:ss");

    for (auto dev : allData)
    {
        QDateTime s = QDateTime::fromString(dev->m_startTime, "yyyy-MM-dd HH:mm:ss");
        QDateTime e = QDateTime::fromString(dev->m_endTime,   "yyyy-MM-dd HH:mm:ss");
        if (s < globalStart) globalStart = s;
        if (e > globalEnd)   globalEnd   = e;
    }

    int totalSeconds = globalStart.secsTo(globalEnd);

    if (totalSeconds <= 0)
        return;
//=================================================================
// 初始化map
//=================================================================
    QMap<qint64, int> mergedMap;
    for (int i = 0; i <= totalSeconds; i++)
    {
        QDateTime t = globalStart.addSecs(i);
        mergedMap.insert(t.toMSecsSinceEpoch(), 0);
    }

//=================================================================
// 将时间数据和对应的数据值保存到map
//=================================================================
    for (auto dev : allData)
    {
        QDateTime devStart = QDateTime::fromString(dev->m_startTime, "yyyy-MM-dd HH:mm:ss");

        for (int i = 0; i < dev->m_data.size(); i++)
        {
            QDateTime t = devStart.addSecs(i);
            qint64 key = t.toMSecsSinceEpoch();

            if (mergedMap.contains(key))
            {
                mergedMap[key] = dev->m_data[i];
            }
        }
    }

//=================================================================
// 图表
//=================================================================
    if (!chart_temperature)
    {
        qDebug() << "创建了图表" << __LINE__ << __FILE_NAME__;
        chart_temperature = new QChart();
    }

    this->chart_temperature->removeAllSeries();
    // this->series_temperature->clear();
//=================================================================
// X轴
//=================================================================

    if (!this->axisX_temperature)
    {
        qDebug() << "创建了x轴" << __LINE__ << __FILE_NAME__;
        this->axisX_temperature = new QDateTimeAxis();
        this->axisX_temperature->setFormat("HH:mm:ss");
        this->axisX_temperature->setTitleText("时间");
        this->chart_temperature->addAxis(axisX_temperature, Qt::AlignBottom);
    }

//=================================================================
// Y轴
//=================================================================
    if (!this->axisY)
    {
        qDebug() << "创建了y轴" << __LINE__ << __FILE_NAME__;
       this->axisY = new QValueAxis();
       this->axisY->setTitleText("数值");
       this->axisY->setTitleText("时间");
       this->chart_temperature->addAxis(this->axisY, Qt::AlignBottom);
    }

    // QValueAxis* axisY = new QValueAxis();
    // axisY->setTitleText("值");
    // this->chart_temperature->addAxis(axisY, Qt::AlignLeft);

//=================================================================
// 折线
//=================================================================
    this->series_temperature = new QLineSeries();
    this->series_temperature->setName("历史数据");

//=================================================================
// 将map的数据添加到折线上
//=================================================================
    int max = mergedMap.begin().value();
    int min = mergedMap.begin().value();
    this->axisY->setRange(min, max);

    for (auto it = mergedMap.begin(); it != mergedMap.end(); ++it)
    {
        if(it.value() > max)
        {
            max = it.value();
            this->axisY->setRange(min, max);
        }
        if(it.value() < min)
        {
            min = it.value();
            this->axisY->setRange(min, max);
        }
        this->series_temperature->append(it.key(), it.value());
    }

//=================================================================
// 图表添加折线，折线绑定X轴和Y轴
//=================================================================
    this->chart_temperature->addSeries(this->series_temperature);
    this->series_temperature->attachAxis(axisX_temperature);
    this->series_temperature->attachAxis(axisY);
    this->axisX_temperature->setRange(globalStart, globalEnd);

    if (this->chartView_temperature)
    {
        qDebug() << "创建了视图" << __LINE__ << __FILE_NAME__;
        this->chartView_temperature->setChart(chart_temperature);
    }
    qDebug() << "绘制完成" << __LINE__ << __FILE_NAME__;
}
